﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace Mengsk.ProxyDelivery.Converters
{
    public class VendorDoorConverter : IValueConverter
    {
        private VendorService vendorService = ServiceContainer.GetService<VendorService>();
        private ShoesService shoesService = ServiceContainer.GetService<ShoesService>();

        private static readonly Dictionary<string, string> vendors = new Dictionary<string, string>();


        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return "";
            }

            string name = value.ToString();
            if (vendors.ContainsKey(name))
            {
                return vendors[name];
            }

            lock (vendors)
            {
                if (vendors.ContainsKey(name))
                {
                    return vendors[name];
                }

                var vendor = this.vendorService.GetByName(name);

                if (vendor == null || vendor.Count < 1)
                {
                    vendor = this.vendorService.GetAllByFieldLike("name", VendorService.FormatVendorName(name), 0, 0).Datas;
                }

                if (vendor == null || vendor.Count < 1)
                {
                    return "---";
                }

                if (vendor.Count > 1)
                {
                    return "厂家重复";
                }

                string door = VendorService.FormatVendorDoor(vendor[0].MarketAddress);
                if (string.IsNullOrWhiteSpace(door))
                {
                    door = "---";
                }
                vendors[name] = door;
                return door;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
